package com.steel.yfmall.cloud.assistant.utils;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * @program: HttpSendUtil
 * @author: liuzhijun
 * @date: 2021-03-23 20:15
 **/
public class HttpSendUtil {


    private static Logger logger = LoggerFactory.getLogger(HttpSendUtil.class);

    /**
     * 发送POST请求
     *
     * @param urlStr
     * @param param
     * @return String
     */
    public static String sendPost(String urlStr, String param) {
        PrintWriter out = null;
        BufferedReader in = null;

        StringBuilder result = new StringBuilder();

        try {
            URL url = new URL(urlStr);
            HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
            //设置参数
            //需要输出
            httpConn.setDoOutput(true);
            //需要输入
            httpConn.setDoInput(true);
            //设置POST方式连接
            httpConn.setRequestMethod("POST");
            //设置请求属性
            httpConn.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
            //建立输入流，向指向的URL传入参数
            DataOutputStream dos = new DataOutputStream(httpConn.getOutputStream());
            dos.write(param.getBytes("utf-8"));
            dos.flush();
            dos.close();

            //获得响应状态
            int resultCode = httpConn.getResponseCode();
            if (HttpURLConnection.HTTP_OK == resultCode) {
                String readLine;
                BufferedReader responseReader = new BufferedReader(new InputStreamReader(httpConn.getInputStream(), "UTF-8"));
                while ((readLine = responseReader.readLine()) != null) {
                    result.append(readLine).append("\n");
                }
                responseReader.close();
            }
        } catch (Exception e) {
            logger.error("发送POST请求异常:" + urlStr, e);
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }

        return result.toString();
    }

    /**
     * 发送POST请求
     *
     * @param urlStr
     * @param param
     * @return String
     */
    public static String sendXmlPost(String urlStr, String param) {
        PrintWriter out = null;
        BufferedReader in = null;

        StringBuilder result = new StringBuilder();
        String res = null;
        try {
            URL url = new URL(urlStr);
            HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
            //设置参数
            //需要输出
            httpConn.setDoOutput(true);
            //需要输入
            httpConn.setDoInput(true);


            // 设置不用缓存
            httpConn.setUseCaches(false);
            // 设置传递方式
            httpConn.setRequestMethod("POST");
            // 设置维持长连接
            httpConn.setRequestProperty("Connection", "Keep-Alive");
            // 设置文件字符集:
            // 转换为字节数组
            byte[] data = param.getBytes("utf-8");
            // 设置文件长度
            httpConn.setRequestProperty("Content-Length", String.valueOf(data.length));
            // 设置文件类型:
            httpConn.setRequestProperty("Content-Type", "application/xml;charset=UTF-8");

            //建立输入流，向指向的URL传入参数
            DataOutputStream dos = new DataOutputStream(httpConn.getOutputStream());
//            OutputStreamWriter dos = new OutputStreamWriter(httpConn.getOutputStream());
            // 写入请求的字符串
            dos.write(data);
            dos.flush();
            dos.close();

            //获得响应状态
            int resultCode = httpConn.getResponseCode();
            System.out.println("状态码： " + resultCode);
            if (HttpURLConnection.HTTP_OK == resultCode) {
                String readLine;
                BufferedReader responseReader = new BufferedReader(new InputStreamReader(httpConn.getInputStream(), "UTF-8"));
                while ((readLine = responseReader.readLine()) != null) {
                    result.append(readLine).append("\n");
                }
                responseReader.close();
            }
        } catch (Exception e) {
            result.append("发送POST请求异常!" + e);
            e.printStackTrace();
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }

        return result.toString();
    }

    /**
     * 发送https请求
     *
     * @param requestUrl    请求地址
     * @param requestMethod 请求方式（GET、POST）
     * @param outputStr     提交的数据
     * @return JSONObject(通过JSONObject.get ( key)的方式获取json对象的属性值)
     */
//    public static JSONObject httpsRequest(String requestUrl, String requestMethod, String outputStr) {
//        JSONObject jsonObject = null;
//        try {
//            // 创建SSLContext对象，并使用我们指定的信任管理器初始化
//            TrustManager[] tm = {new MyX509TrustManager()};
//            SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
//            sslContext.init(null, tm, new java.security.SecureRandom());
//            // 从上述SSLContext对象中得到SSLSocketFactory对象
//            SSLSocketFactory ssf = sslContext.getSocketFactory();
//            String strUrl = requestUrl.replaceAll("\n", "").replaceAll("\r", "");
//            URL url = new URL(strUrl);
//            HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
//            conn.setSSLSocketFactory(ssf);
//            conn.setDoOutput(true);
//            conn.setDoInput(true);
//            conn.setUseCaches(false);
//            // 设置请求方式（GET/POST）
//            conn.setRequestMethod(requestMethod);
//            // 当outputStr不为null时向输出流写数据
//            if (null != outputStr) {
//                OutputStream outputStream = conn.getOutputStream();
//                // 注意编码格式
//                outputStream.write(outputStr.getBytes("UTF-8"));
//                outputStream.close();
//            }
//            // 从输入流读取返回内容
//            InputStream inputStream = conn.getInputStream();
//            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
//            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
//            String str = null;
//            StringBuffer buffer = new StringBuffer();
//            while ((str = bufferedReader.readLine()) != null) {
//                buffer.append(str);
//            }
//            // 释放资源
//            bufferedReader.close();
//            inputStreamReader.close();
//            inputStream.close();
//            inputStream = null;
//            conn.disconnect();
//            jsonObject = JSONObject.parseObject(buffer.toString());
//        } catch (ConnectException ce) {
//            ce.printStackTrace();
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        return jsonObject;
//    }

    /**
     * 发送POST请求
     *
     * @param urlStr
     * @param param
     * @return String
     */
    public static String sendPost(String urlStr, String param, String format) {
        PrintWriter out = null;
        BufferedReader in = null;

        StringBuilder result = new StringBuilder();

        try {
            URL url = new URL(urlStr);
            HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
            //设置参数
            httpConn.setDoOutput(true);   //需要输出
            httpConn.setDoInput(true);   //需要输入
            httpConn.setRequestMethod("POST");   //设置POST方式连接
            if (StringUtils.isBlank(format)) {
                format = "application/x-www-form-urlencoded;charset=UTF-8";
            }
            //设置请求属性"application/json;charset=UTF-8"
            httpConn.setRequestProperty("Content-Type", format);
            //建立输入流，向指向的URL传入参数
            DataOutputStream dos = new DataOutputStream(httpConn.getOutputStream());
            dos.write(param.getBytes("utf-8"));
            dos.flush();
            dos.close();

            //获得响应状态
            int resultCode = httpConn.getResponseCode();
            if (HttpURLConnection.HTTP_OK == resultCode) {
                String readLine;
                BufferedReader responseReader = new BufferedReader(new InputStreamReader(httpConn.getInputStream(), "UTF-8"));
                while ((readLine = responseReader.readLine()) != null) {
                    result.append(readLine).append("\n");
                }
                responseReader.close();
            }
        } catch (Exception e) {
            result.append("发送POST请求异常!" + e);
            e.printStackTrace();
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }

        return result.toString();
    }

    /**
     * 发送post请求
     * @param url 请求地址
     * @param params 请求数据
     * @param timeOut 超时时间
     * @return String
     */
    public static String sendPost(String url, Map<String, String> params, int timeOut) {

        //设置参数
        List<NameValuePair> list = new ArrayList<NameValuePair>();
        Iterator iterator = params.entrySet().iterator();

        while(iterator.hasNext()){
            Map.Entry<String, String> elem = (Map.Entry<String, String>) iterator.next();
            list.add(new NameValuePair(elem.getKey(),elem.getValue()));
        }

        NameValuePair[] pairs = new NameValuePair[list.size()];
        pairs = list.toArray(pairs);

        return sendPost(url, pairs);
    }

    /**
     * 发送post请求
     *
     * @return java.lang.String
     * @params [url, data]
     * @author Enzo
     * @date 2019-5-15
     */
    public static String sendPost(String url, NameValuePair[] data) {
        return sendPost(url, data, -1);
    }

    /**
     * 设置post请求
     * @param url 请求地址
     * @param data 请求数据
     * @param timeOut 超时时间
     * @return String
     */
    public static String sendPost(String url, NameValuePair[] data, int timeOut) {
        String result = null;
        HttpClient client = new HttpClient();
        if (timeOut <= 0) {
            timeOut = 30;
        }
        client.getHttpConnectionManager().getParams().setSoTimeout(timeOut);
        PostMethod post = new PostMethod(url);
        //在头文件中设置转码
        post.addRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=gbk");
        post.setRequestBody(data);
        try {
            client.executeMethod(post);
            result = new String(post.getResponseBodyAsString());
            post.releaseConnection();
        } catch (Exception e) {
            logger.error("请求失败", e);
        }
        return result;
    }

}
